//
//  LiveNewSignViewModelSec.m
//  AFNetworking
//
//  Created by tianlong on 2020/9/27.
//

#import "LiveNewSignViewModelSec.h"
#import "LiveNewSignViewSec.h"
#import "LiveNewMyClassConfig.h"
#import "Masonry.h"


@interface LiveNewSignViewModelSec ()
@property (strong, nonatomic) WXAnimationManager *aniManager;
@property (weak,   nonatomic) UIView *bindSignView;
@property (assign, nonatomic) CGRect lastFrame;
@property (weak,   nonatomic) UIView *bindCloseBtn;
@property (weak,   nonatomic) UIButton *closeBtn;
@property (assign, nonatomic) CGRect lastCloseFrame;
@end

@implementation LiveNewSignViewModelSec

static NSString *signShowJson = @"livenewsign_show";
static NSString *signWaitJson = @"livenewsign_wait";
static NSString *signDoneNoTitleJson = @"livenewsign_done";
static NSString *signDoneWithTitleJson = @"livenewsign_done_withTitle";

#pragma mark - 通知回调
- (void)appWillResignActive:(NSNotification *)note {
    [super appWillResignActive:note];
    if ([self.aniManager getAnimationByIdentifier:signDoneNoTitleJson] || [self.aniManager getAnimationByIdentifier:signDoneWithTitleJson]) {
        [self signDoneAnimationFinishedTodo];
    }
    else if ([self.aniManager getAnimationByIdentifier:signShowJson]) {
        [self.aniManager stopAniamtionWithIdentifier:signShowJson];
        [self playAnimteSignWait];
    }
}

#pragma mark - 签到面板

//展示签到
- (void)showSignViewWithInterId:(NSString *)interId {
    if ([self.aniManager getAnimationByIdentifier:signShowJson] ||
        [self.aniManager getAnimationByIdentifier:signWaitJson] ||
        [self.aniManager getAnimationByIdentifier:signDoneNoTitleJson] ||
        [self.aniManager getAnimationByIdentifier:signDoneWithTitleJson]) {
        return;
    }
    [self playAnimteSignShow];
//    [LiveLogStatisticsHandler liveNewSignLog_startWithWithNonce:[self getNonce] interactiveid:interId];
}

- (void)playAnimteSignShow {
    __weak typeof(self)selfWeak = self;
    [self.aniManager playWithJson:signShowJson speed:1 repeatCount:0 identifier:signShowJson fromFrame:[NSNumber numberWithInt:0] toFrame:[NSNumber numberWithInt:60] layout:^(WXAnimationView *aniView) {
        [selfWeak configAnimationView:aniView aniJson:signShowJson signMsg:nil];
    } autoPlay:YES completion:^(BOOL finished) {
        [selfWeak.aniManager stopAniamtionWithIdentifier:signShowJson];
        [selfWeak playAnimteSignWait];
    }];
}

//等待签到
- (void)playAnimteSignWait {
    
    if ([self.aniManager getAnimationByIdentifier:signWaitJson]) {
        return;
    }
    
    [self removeSignView];
   
    __weak typeof(self)selfWeak = self;
    [self.aniManager playWithJson:signWaitJson speed:1 repeatCount:INT_MAX identifier:signWaitJson layout:^(WXAnimationView *aniView) {
        [selfWeak configAnimationView:aniView aniJson:signWaitJson signMsg:nil];
    } autoPlay:YES completion:nil];
}

//签到完成
- (void)playAnimteSignDone {
    
    [self removeSignView];
    
    __weak typeof(self)selfWeak = self;
    [self.aniManager playWithJson:signDoneNoTitleJson speed:1 repeatCount:INT_MAX identifier:signDoneNoTitleJson layout:^(WXAnimationView *aniView) {
        [selfWeak configAnimationView:aniView aniJson:signDoneNoTitleJson signMsg:nil];
    } autoPlay:YES completion:nil];
}

- (void)showSignSuccessWithoutTitle:(NSString *)signMsg {
    if ([self.aniManager getAnimationByIdentifier:signDoneNoTitleJson]) {
        return;
    }
    
    [self removeSignView];
   
    __weak typeof(self)selfWeak = self;
    [self.aniManager playWithJson:signDoneNoTitleJson speed:1 repeatCount:0 identifier:signDoneNoTitleJson layout:^(WXAnimationView *aniView) {
        [selfWeak configAnimationView:aniView aniJson:signDoneNoTitleJson signMsg:signMsg];
    } autoPlay:YES completion:^(BOOL finished) {
        [selfWeak signDoneAnimationFinishedTodo];
    }];
}

- (void)showSignSuccessWithTitle:(LiveNewSignTitleEntity *)titleEntity stuName:(NSString *)stuName {
    if ([self.aniManager getAnimationByIdentifier:signDoneWithTitleJson]) {
        return;
    }
    
    if (!self.inView) {
        return;
    }
    
    [self removeSignView];
   
    __weak typeof(self)selfWeak = self;
    [self.aniManager playWithJson:signDoneWithTitleJson speed:1 repeatCount:0 identifier:signDoneWithTitleJson layout:^(WXAnimationView *aniView) {
        aniView.backgroundImageView.hidden = NO;
        aniView.backgroundImageView.backgroundColor = [UIColor blackColor];
        aniView.backgroundImageView.alpha = 0.45;
        aniView.delegate = self;

        if (self.inView) {
            [self addAniView:aniView inView:self.inView aboveView:self.aboveView];
//            [self.inView addSubview:aniView];
            CGFloat realH = [LiveSizeConfig getPPTHeight];
            [aniView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.left.bottom.right.offset(0);
            }];
            [aniView.playView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.center.equalTo(aniView);
                make.width.offset(realH);
                make.height.offset(realH);
            }];
            //签到学生姓名
            CGRect rect = [stuName boundingRectWithSize:CGSizeMake(MAXFLOAT, 38) options: NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName :[UIFont boldSystemFontOfSize:38]} context:nil];
            CGFloat labelW = rect.size.width + 1;
            labelW = labelW >=10 ? labelW : 10;
            labelW = labelW<=115? labelW : 115;

            UIView *titleView = [[UIView alloc] init];
            UILabel *nameLabel = [[UILabel alloc] init];
            nameLabel.text = [NSString stringWithFormat:stuName];
            nameLabel.font = [UIFont fontPingFangSCWithSize:36];
            nameLabel.textColor = [UIColor colorWithHexValue:0xD16B28];
            [titleView addSubview:nameLabel];
            [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.mas_equalTo(0);
                make.left.mas_equalTo(68);
                make.width.mas_equalTo(labelW);
            }];

            //签到进场文案
            UILabel *descriptionLabel = [[UILabel alloc] init];
            descriptionLabel.text = [NSString stringWithFormat:@"进入直播间"];
            descriptionLabel.font = [UIFont fontPingFangSCWithSize:36];
            descriptionLabel.textColor = [UIColor colorWithHexValue:0xD16B28];
            [titleView addSubview:descriptionLabel];
            [descriptionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.mas_equalTo(0);
                make.left.mas_equalTo(nameLabel.mas_right);
                make.right.mas_equalTo(0);
            }];

            [aniView bindingUIView:titleView forKeyPath:@"矩形.png" imageName:@"livenewsign_done_withTitle_img_14.png"];
        }
    } autoPlay:YES completion:^(BOOL finished) {
        [selfWeak signDoneAnimationFinishedTodo];
    }];
    
}

#pragma mark - private function
/* 签完到要做的事 */
- (void)signDoneAnimationFinishedTodo {
    if (self.signViewWillDismissBlock) {
        self.signViewWillDismissBlock([(LiveNewSignViewSec *)self.signView headView]);
    }
    [self removeSignView];
}

/* 配置动画视图基本属性 */
- (void)configAnimationView:(WXAnimationView *)aniView aniJson:(NSString *)aniJson signMsg:(NSString *)signMsg {
    __weak typeof(self)selfWeak = self;
    aniView.backgroundImageView.hidden = NO;
    aniView.backgroundImageView.backgroundColor = [UIColor blackColor];
    aniView.backgroundImageView.alpha = 0.45;
    aniView.delegate = self;
    
    if (self.inView) {
        [self addAniView:aniView inView:self.inView aboveView:self.aboveView];
//        [self.inView addSubview:aniView];
        CGFloat realW = 550 *0.5 *aniView.bigClassScale;
        CGFloat realH = 550 *0.5 *aniView.bigClassScale;
        [aniView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.left.bottom.right.offset(0);
        }];
        [aniView.playView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(aniView);
            make.width.offset(realW);
            make.height.offset(realH);
        }];
    }
    
    UIView *bindSignView = [[UIView alloc] init];;
    NSString *bindSignPath = @"签到成功弹窗@2x.png";
    NSString *bindSignName = nil;
    
    UIView *bindCloseBtn = [[UIView alloc] init];
    NSString *bindClosePath = @"btn-关闭@2x.png";
    NSString *bindCloseName = nil;
    
    if ([aniJson isEqualToString:signShowJson]) {
        bindSignName = @"livenewsign_show_8.png";
        bindCloseName = @"livenewsign_show_4.png";
    }
    else if([aniJson isEqualToString:signWaitJson]) {
        bindSignName = @"livenewsign_wait_8.png";
        bindCloseName = @"livenewsign_wait_4.png";
    }
    else if([aniJson isEqualToString:signDoneNoTitleJson]) {
        bindSignName = @"livenewsign_done_9.png";
        bindCloseName = @"livenewsign_done_5.png";
    }
    
    [aniView bindingUIView:bindSignView forKeyPath:bindSignPath imageName:bindSignName];
    self.bindSignView = bindSignView;
    
    [aniView bindingUIView:bindCloseBtn forKeyPath:bindClosePath imageName:bindCloseName];
    self.bindCloseBtn = bindCloseBtn;
    
    if ([aniJson isEqualToString:signWaitJson] ||
        [aniJson isEqualToString:signDoneNoTitleJson]) {
        [selfWeak configShowSignViewWithAniView:aniView];
        selfWeak.signView.frame = selfWeak.lastFrame;
        selfWeak.closeBtn.frame = selfWeak.lastCloseFrame;
    }
    
    if ([aniJson isEqualToString:signDoneNoTitleJson]) {
        [(LiveNewSignViewSec *)selfWeak.signView descLabel].hidden = YES;
        [(LiveNewSignViewSec *)selfWeak.signView signBtn].hidden = YES;
        [(LiveNewSignViewSec *)selfWeak.signView nameLabel].hidden = YES;
        [(LiveNewSignViewSec *)selfWeak.signView tipLabel].hidden = NO;
        if (signMsg) {
            [(LiveNewSignViewSec *)selfWeak.signView tipLabel].text = signMsg;
        }
    }
}

- (void)addAniView:(UIView *)subAniView inView:(UIView *)inView aboveView:(UIView *)aboveSubView {
    if (!inView || !subAniView) {
        return;
    }
    [inView addSubview:subAniView];
    if (aboveSubView && aboveSubView.superview == inView) {
        [inView insertSubview:subAniView belowSubview:aboveSubView];
    }
}

#pragma mark - event
- (void)clickedCloseButton:(UIButton *)button {
    if (self.signViewWillDismissBlock) {
        self.signViewWillDismissBlock([(LiveNewSignViewSec *)self.signView headView]);
    }
    if (self.didClickedClosedBlock) {
        self.didClickedClosedBlock();
    }
    [self removeSignView];
    NSLog(@"myclass -- 点击了签到面板上的关闭按钮");
}

#pragma mark - public function
/* 签到成功 */
- (void)showSignSuccess:(LiveNewSignSuccessEntity *)successEntity myClassStatus:(BOOL)myClassStatus {
    NSString *signStatus = !myClassStatus ? @"1" : @"2";
    
    if (successEntity && successEntity.isSupportClassPk && !myClassStatus) {
        if (![NSArray isEmptyArray:successEntity.title]) {
            LiveNewSignTitleEntity *titleEntity = successEntity.title.firstObject;
            if (titleEntity && titleEntity.type == 1) {
                //一期只展示智多星称号，其余情况都展示普通签到动效
                NSString *stuName = successEntity.name;
                if (!stuName || stuName.length <= 0) {
                    stuName = @"网校学员";
                }
                [self showSignSuccessWithTitle:titleEntity stuName:stuName];
                
//                [LiveLogStatisticsHandler liveNewSignLog_SignSuccessWithSignStatus:signStatus titleStatus:[NSString stringWithFormat:@"%d", titleEntity.type] nonce:self.nonce interactiveid:self.interactionId];
                return;
            }
        }
        NSString *signTipMsg = @"签到成功~";
        if (successEntity.signMessage && successEntity.signMessage.length > 0) {
            signTipMsg = successEntity.signMessage;
        }
        [self showSignSuccessWithoutTitle:signTipMsg];
//        [LiveLogStatisticsHandler liveNewSignLog_SignSuccessWithSignStatus:signStatus titleStatus:@"0" nonce:self.nonce interactiveid:self.interactionId];
    } else {
        [self showSignSuccessWithoutTitle:@"签到成功~"];
//        [LiveLogStatisticsHandler liveNewSignLog_SignSuccessWithSignStatus:signStatus titleStatus:@"0" nonce:self.nonce interactiveid:self.interactionId];
    }
}

- (void)showSignMiss{
    [self removeSignView];
//    [LiveNewToastView showNewToastWithTitle:@"错过签到啦~"];
}

- (void)showSignNot{/** 新版去掉了 */}

- (void)removeSignView {
    [super removeSignView];
    [self.closeBtn removeFromSuperview];
    self.closeBtn = nil;
    [self.aniManager stopAllAnimations];
}

#pragma mark - animationViewDelegate
- (void)animationViewDidPlay:(WXAnimationView *)animationView jsonName:(NSString *)jsonName {
    {
        if ([jsonName isEqualToString:signShowJson]) {
            [self configShowSignViewWithAniView:animationView];
            {//签到面板
                CGRect frame = [animationView convertElementLayerFrameToAnimationLayer:self.bindSignView.layer];
                frame = [animationView convertRect:frame fromView:animationView.playView];
                if (![NSStringFromCGRect(frame) isEqualToString:NSStringFromCGRect(self.lastFrame)]) {
                    self.lastFrame = frame;
                }
                self.signView.frame = frame;
            }
            
            {//关闭按钮
                CGRect frame = [animationView convertElementLayerFrameToAnimationLayer:self.bindCloseBtn.layer];
                frame = [animationView convertRect:frame fromView:animationView.playView];
                if (![NSStringFromCGRect(frame) isEqualToString:NSStringFromCGRect(self.lastCloseFrame)]) {
                    self.lastCloseFrame = frame;
                }
                self.closeBtn.frame = frame;
            }
        }
    }
}

- (void)configShowSignViewWithAniView:(WXAnimationView *)aniView {
    if (!self.signView) {
        __weak typeof(self)selfWeak = self;
        LiveNewSignViewSec *signView = [[LiveNewSignViewSec alloc] initWithStuName:self.stuName stuAvatar:self.stuAvatar];
        [signView setClickedSignButtonBlock:^{
            NSLog(@"myclass -- 点击了签到按钮");
            if (selfWeak.didClickedSignBlock) {
                selfWeak.didClickedSignBlock();
            }
        }];
        
        [signView setClickedCloseButtonBlock:^{
            NSLog(@"myclass -- 点击了关闭按钮");
            if (selfWeak.didClickedClosedBlock) {
                selfWeak.didClickedClosedBlock();
            }
        }];
        [aniView addSubview:signView];
        self.signView = signView;
    }
    
    if (!self.closeBtn) {
        UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [closeBtn setImage:[UIImage imageNamed:@"livenew_mycalss_close"] forState:UIControlStateNormal];
        [closeBtn addTarget:self action:@selector(clickedCloseButton:) forControlEvents:UIControlEventTouchUpInside];
        [aniView addSubview:closeBtn];
        self.closeBtn = closeBtn;
    }
}

#pragma mark - getter and setter
- (WXAnimationManager *)aniManager {
    if (!_aniManager) {
        _aniManager = [[WXAnimationManager alloc] init];
    }
    return _aniManager;
}

@end
